package com.imay.live.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.support.annotation.DrawableRes;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.ImageView;

import com.imay.live.R;

import java.lang.ref.WeakReference;

/**
 * Created by chan on 2017/7/25 0025.
 */

public class RoundImageView extends ImageView {

    private WeakReference<Bitmap> mBufferBitmap;

    private Bitmap mMaskBitmap;
    private Paint mPaint;
    private float roundy;
    private float roundx;
    private PorterDuffXfermode mXfermode = new PorterDuffXfermode(PorterDuff.Mode.DST_IN);
    private Bitmap mBitmap;
    private boolean mReady;
    private boolean mSetupPending;


    public RoundImageView(Context context) {
        this(context, null);
    }

    public RoundImageView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RoundImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context, attrs);
    }

    public void initView(Context context, AttributeSet attrs) {
        if (attrs != null) {
            TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RoundTextView);
            roundy = a.getDimension(R.styleable.RoundTextView_t_roundy, context.getResources().getDimension(R.dimen.roundxy));
            roundx = a.getDimension(R.styleable.RoundTextView_t_roundx, context.getResources().getDimension(R.dimen.roundxy));
            a.recycle();
        }

        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setColor(Color.TRANSPARENT);

        mReady = true;

        if (mSetupPending) {
            setup();
            mSetupPending = false;
        }
    }

    private void setup() {
        if (!mReady) {
            mSetupPending = true;
            return;
        }
        //防止空指针异常
        if (mBitmap == null) {
            return;
        }

        invalidate();
    }

    @Override
    public void setImageBitmap(Bitmap bm) {
        super.setImageBitmap(bm);
        mBitmap = bm;
        setup();
    }

    @Override
    public void setImageDrawable(Drawable drawable) {
        super.setImageDrawable(drawable);
        if(drawable == null){
            return;
        }
        mBitmap = drawableToBitmap(drawable);
        System.out.println("setImageDrawable -- setup");
        setup();
    }

    @Override
    public void setImageResource(@DrawableRes int resId) {
        super.setImageResource(resId);
        if(getDrawable() == null){
            return;
        }
        mBitmap = drawableToBitmap(getDrawable());
        setup();
    }

    @Override
    public void setImageURI(Uri uri) {
        super.setImageURI(uri);
        if(getDrawable() == null){
            return;
        }
        mBitmap = drawableToBitmap(getDrawable());
        setup();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        //super.onDraw(canvas);
        Bitmap bmp = (mBufferBitmap == null ? null : mBufferBitmap.get());
        if (bmp == null || bmp.isRecycled()) {
            /*Bitmap mOut = Bitmap.createBitmap(getMeasuredWidth(),
                    getMeasuredHeight(), Bitmap.Config.ARGB_8888);*/

            //创建画布
            //Canvas drawCanvas = new Canvas(mOut);

            if (mMaskBitmap == null || mMaskBitmap.isRecycled()) {
                mMaskBitmap = getDrawBitmap();
            }

            canvas.drawBitmap(mMaskBitmap, 0, 0, mPaint);

            mPaint.setXfermode(mXfermode);
            //将准备好的bitmap绘制出来
            canvas.drawBitmap(mBitmap, 0, 0, null);
            //bitmap缓存起来，避免每次调用onDraw，分配内存
            mBufferBitmap = new WeakReference<Bitmap>(mBitmap);
        } else {
            canvas.drawBitmap(mBitmap, 0, 0, null);
        }
    }

    private Bitmap getDrawBitmap() {
        Bitmap bitmap = Bitmap.createBitmap(getMeasuredWidth(), getMeasuredHeight(),
                Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(Color.BLACK);
        canvas.drawRoundRect(new RectF(0, 0, getWidth(), getHeight()),
                roundx, roundy, paint);
        return bitmap;
    }

    private static Bitmap drawableToBitmap(Drawable drawable) {
        Bitmap bitmap = Bitmap.createBitmap(
                drawable.getIntrinsicWidth(),
                drawable.getIntrinsicHeight(),
                Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        //canvas.setBitmap(bitmap);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        drawable.draw(canvas);
        return bitmap;
    }
}
